package org.blogwu.learn.algorithm.队列;


public class Queue<E> {

    int size = 0;

    private Node<E> head;

    private Node<E> tail;


    public int size() {
        return this.size;
    }

    /**
     * 判断队列是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return this.size < 1;
    }

    /**
     * 入队
     *
     * @param elment
     */
    void enQueue(E elment) {
        Node<E> newNode = new Node<>(elment);
        // 如果队列中没数据
        if (size < 1) {
            // 如果首节点没初始化
            if (head == null) {
                head = newNode;
                tail = head;
                size++;
                return;
            }
        }
        Node<E> pre = tail;
        newNode.setPrev(pre);
        pre.setNext(newNode);
        tail = newNode;
        size++;
    }

    /**
     * 出队
     *
     * @return
     */
    E deQueue() {
        if (size < 1) return null;
        E vv = head.getItem();
        head = head.next;
        size--;
        return vv;
    }


    /**
     * 获取队列的头元素
     *
     * @return
     */
    E front() {
        if (size < 1) return null;
        return head.item;
    }

    /**
     * 清空
     */
    void clear() {
        head.setNext(null);
        tail = head;
        size = 0;
    }

    // 双向链表
    private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        public Node() {
        }

        public Node(E item) {
            this.item = item;
        }


        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }

        public E getItem() {
            return item;
        }

        public void setItem(E item) {
            this.item = item;
        }

        public Node<E> getNext() {
            return next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }

        public Node<E> getPrev() {
            return prev;
        }

        public void setPrev(Node<E> prev) {
            this.prev = prev;
        }
    }
}
